package com.tsfyun.scm.util;

import cn.hutool.core.util.ReflectUtil;
import com.tsfyun.common.base.enums.ResultCodeEnum;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.security.SecurityUtil;
import com.tsfyun.common.base.util.DeviceUtil;
import com.tsfyun.common.base.util.TsfPreconditions;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @Description:
 * @CreateDate: Created in 2020/9/29 18:09
 */
@Slf4j
public class PermissionUtil{

    /**
     * 客户端校验是否有权限操作数据
     * @param t
     */
    public static void checkClientCustomerPermission(Object t) {
        //必须是登录客户端后才可以
        Long customerId = SecurityUtil.getCurrentCustomerId();
        if(Objects.isNull(customerId) || 0L == customerId) {
            log.error(String.format("当前登录平台：{%s}，没有客户信息", DeviceUtil.getPlatform().getName()));
            throw new ServiceException(ResultCodeEnum.PERMISSION_NO_ACCESS);
        }
        if(Objects.isNull(t)) {
            return;
        }
        if(!ReflectUtil.hasField(t.getClass(),"customerId")) {
            return;
        }
        TsfPreconditions.checkArgument(Objects.equals(customerId,ReflectUtil.getFieldValue(t,"customerId")),new ServiceException(ResultCodeEnum.PERMISSION_CUSTOMER_DATA_NO_ACCESS));
    }

}
